//
//  OnMarkDetailViewController.m
//  BSLCar
//
//  Created by 孙卓 on 15/5/26.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "OnMarkDetailViewController.h"
#import "OnMarketSecondModel.h"
#import "OnMarketDetailModel.h"
#import "OnMarketThirdModel.h"
#import "OnMarketFourthModel.h"
#import "LastComViewController.h"

@interface OnMarkDetailViewController ()

@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, retain) NSMutableArray *firArray;
@property (nonatomic, retain) NSMutableArray *secArray;
@property (nonatomic, retain) NSMutableArray *secondArray;
@property (nonatomic, retain) OnMarketDetailModel *model1;
@property (nonatomic, retain) UIView *tableHearView;

@end

@implementation OnMarkDetailViewController

- (void)dealloc
{
    [_idDetail release];
    [_carName release];
    [_str5 release];
    [_str6 release];
    [_image release];
    [_str7 release];
    [_activityIndicator release];
    [_firArray release];
    [_secArray release];
    [_secondArray release];
    [_model1 release];
    [_tableHearView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = self.carName;
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] autorelease] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(fenxiang)];
    myTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    myTable.delegate = self;
    myTable.dataSource = self;
    myTable.backgroundColor = [UIColor whiteColor];
    self.tableHearView = [[UIView alloc] initWithFrame:CGRectMake(0, 2, self.view.bounds.size.width, 170)];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = self.view.center;
    [self.view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
#pragma 网络请求和解析写在这里
    //创建一个数组
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *cityID = [user objectForKey:@"cityid"];
    NSString *provinceId = nil;
    if ([cityID isEqualToString:@"0"]) {
        provinceId = cityID;
    } else{
        provinceId = [cityID substringToIndex:2];
        provinceId = [NSString stringWithFormat:@"%@0000",provinceId];
    }
    NSString *str = @"http://baojia.qichecdn.com/priceapi3.9.2/services/seriessummary/get?seriesid=";
    str = [NSString stringWithFormat:@"%@%@&provinceid=%@&cityid=%@&salestate=1",str,self.idDetail, provinceId, cityID];

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:40];
    request.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //开始解析：
        //解析里面的难点：
        //用json解析的方法
        if (!connectionError) {
#pragma -mark 给model赋值
            connectionError = nil;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
#pragma -mark result里面的model赋值
            if (!connectionError) {
                NSDictionary *dic1 = [dic objectForKey:@"result"];
                self.model1 = [[OnMarketDetailModel alloc] init];
                self.model1.title = [dic1 objectForKey:@"fctname"];
                self.model1.priceSection = [dic1 objectForKey:@"fctprice"];
                self.model1.levelName = [dic1 objectForKey:@"levelname"];
                self.model1.Img = [dic1 objectForKey:@"logo"];
                self.model1.picCount = [[dic1 objectForKey:@"piccount"] stringValue];
                NSArray *array = [dic1 objectForKey:@"enginelist"];
#pragma -mark englist(array)里面的model赋值
                self.firArray = [NSMutableArray array];
                self.secArray = [NSMutableArray array];
                self.secondArray = [NSMutableArray array];
                for (NSDictionary *dic2 in array) {
                    OnMarketSecondModel *model2 = [[OnMarketSecondModel alloc] init];
                    model2.lanuchName = [dic2 objectForKey:@"name"];
                    [self.firArray addObject:model2];
                    NSArray *array2 = [dic2 objectForKey:@"speclist"];
#pragma -mark 给第三个model赋值
                    for (NSDictionary *dic3 in array2) {
                        OnMarketThirdModel *model3 = [[OnMarketThirdModel alloc] init];
                        model3.lowerPrice = [dic3 objectForKey:@"dealerprice"];
                        model3.TypeName = [dic3 objectForKey:@"name"];
                        model3.detailImg = [dic3 objectForKey:@"speclogo"];
                        model3.idNumber = [dic3 objectForKey:@"id"];
                        [self.secArray addObject:model3];

#pragma -mark 给第四个model赋值
                        
                        NSDictionary *dic4 = [dic3 objectForKey:@"pricedetails"];
                        OnMarketFourthModel *model4 = [[OnMarketFourthModel alloc] init];
                        if ([dic4 isKindOfClass:[NSDictionary class]]) {
                            model4.instructPrice = [dic4 objectForKey:@"referenceprice"];
                        } else {
                            model4.instructPrice = @"0";
                        }
                        [self.secondArray addObject:model4];
                    }
                }
                [self.activityIndicator stopAnimating];
                [self createTableView];
            } else {
                [self.activityIndicator stopAnimating];
                [self notDataView];
            }
        } else {
            [self.activityIndicator stopAnimating];
            [self notDataView];
        }
    }];
    
    [_activityIndicator release];
}

- (void)click:(UIButton *)sender {
    LastComViewController *lastview = [[LastComViewController alloc] init];
    [self.navigationController pushViewController:lastview animated:YES];
    lastview.serid = self.idDetail;
    lastview.name = self.model1.title;
    lastview.sp = @"0";
    [lastview release];
}

- (void)notDataView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
    label.text = @"目前没有您想要的数据";
    [self.view addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
    label.center = self.view.center;
    [label release];
}

- (void)createTableView {
    
    myTable.delegate = self;
    myTable.dataSource = self;
    [self.view addSubview:myTable];
    //分割线
    myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self createTableHearderView];
    myTable.tableHeaderView = self.tableHearView;
    
    [myTable release];
    [_tableHearView release];
}

- (void)createTableHearderView {
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2, self.view.bounds.size.width - 4, 165)];
    image.layer.cornerRadius = 3;
    image.layer.masksToBounds = YES;
    NSURL *url = [NSURL URLWithString:self.model1.Img];
    [image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];

    self.str7 =self.model1.Img;
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 4, self.view.bounds.size.width / 3 + 30, 20)];
    label2.textColor = [UIColor blackColor];
    label2.backgroundColor = [UIColor grayColor];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.text = self.model1.title;
    UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(10, 145, 100, 20)];
    label4.text = self.model1.levelName;
    label4.textColor = [UIColor redColor];
    UILabel *label6 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - self.view.bounds.size.width / 3 - 65, 146, self.view.bounds.size.width / 3 + 60, 20)];
    label6.backgroundColor = [UIColor grayColor];
    label6.textColor = [UIColor yellowColor];
    label6.font = [UIFont systemFontOfSize:15];
    label6.textAlignment = NSTextAlignmentCenter;
    NSString *strr = @"价格区间: ";
    if (!([self.model1.priceSection isEqualToString:@"暂无"] || [self.model1.priceSection isEqualToString:@"停售"])) {
        strr = [NSString stringWithFormat:@"%@%@万", strr, self.model1.priceSection];
    } else {
        strr = [NSString stringWithFormat:@"%@  暂无", strr];
    }
    label6.text = strr;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.view.bounds.size.width - 115, 15, 100, 60);
    button.titleLabel.textAlignment = NSTextAlignmentRight;
    button.titleLabel.numberOfLines = 0;
    [button.titleLabel sizeToFit];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:[NSString stringWithFormat:@"%@张图片", self.model1.picCount] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonNull = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNull.frame = self.tableHearView.frame;
    buttonNull.backgroundColor = [UIColor clearColor];
    [buttonNull addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.tableHearView addSubview:image];
    [self.tableHearView addSubview:label2];
    [self.tableHearView addSubview:label4];
    [self.tableHearView addSubview:label6];
    [self.tableHearView addSubview:button];
    [self.tableHearView addSubview:buttonNull];
    
    [image release];
    [label2 release];
    [label4 release];
    [label6 release];
}

#pragma -markTableView方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell0";
    OnMarketDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[OnMarketDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
#pragma -mark 给cell赋
    OnMarketThirdModel *model2 = [self.secArray objectAtIndex:indexPath.row];
    NSString *str2 = [NSString stringWithFormat:@"最低价格: %@万",model2.lowerPrice];
    cell.lowPriceLabel.text = str2;
    cell.engTypeLabel.text = model2.TypeName;
   // NSLog(@"%@", model2.TypeName);
    [cell.detailImage sd_setImageWithURL:[NSURL URLWithString:model2.detailImg] placeholderImage:[UIImage imageNamed:@"Bei"]];
    OnMarketFourthModel *model3 = [self.secondArray objectAtIndex:indexPath.row];
    NSString *str5 = @"指导价:";
    self.str6 = model2.TypeName;
    if (![model3.instructPrice isEqualToString:@"0"]) {
        str5 = [NSString stringWithFormat:@"%@ %@万", str5, model3.instructPrice];
    } else {
        str5 = [NSString stringWithFormat:@"%@ 暂无", str5];
    }
    cell.insPriceLabel.text = str5;

    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.firArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    OnMarketSecondModel *model2 = [self.firArray objectAtIndex:section];
    return  model2.lanuchName;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.secArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 160;
}
- (void)fenxiang
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"556343f267e58ed117001f59"
                                      shareText:self.str6
                                     shareImage:self.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, nil]
                                       delegate:self];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OnMarketThirdModel *model = [self.secArray objectAtIndex:indexPath.row];
    OnMarkThirdViewController *th = [[OnMarkThirdViewController alloc]init];
    th.str = model.idNumber;
    th.title = self.str6;

    [self.navigationController pushViewController:th animated:YES];
    [th release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
